package xuegao.study.mall.gateway.filter;

import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

/**
 * 该过滤器用于生成traceId
 */
@Component
public class TraceIdGlobalFilter implements GlobalFilter, Ordered {

    private final String TRACE_ID = "traceId";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String traceId = exchange.getRequest().getHeaders().getFirst(TRACE_ID);
        if (!StringUtils.hasText(traceId)) {
            // 给request设置请求头
            ServerHttpRequest req = exchange.getRequest().mutate().headers(httpHeaders -> {
                //httpHeaders 封装了所有的请求头
                String myTraceId = genTraceId();
                MDC.put(TRACE_ID, myTraceId);
                httpHeaders.set(TRACE_ID, myTraceId);
            }).build();
            //设置增强的request到exchange对象中
            exchange.mutate().request(req);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }

    private String genTraceId() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
